/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int depth = 0;
        return dfs(root, depth);

    }

    bool dfs(TreeNode *root, int &depth) {
        if (root == NULL) {
            depth = 0;
            return true;
        }

        int leftDepth = 0;
        int rightDepth = 0;
        if (!dfs(root->left, leftDepth) ||
            !dfs(root->right, rightDepth)) {
            return false;
        }
        if (abs(leftDepth - rightDepth) > 1) {
            return false;
        }
        if (leftDepth > rightDepth) {
            depth = leftDepth + 1;
        } else {
            depth = rightDepth + 1;
        }
        return true;
    }
};
